<?php
namespace app\common\service\ActivityService;

use app\Normal;
use app\model\BbcModel\Activity;
use app\model\BbcModel\ActivityBook;
use app\model\BbcModel\ActivityDiscount;
use app\model\BbcModel\ActivityDrop;
use app\model\BbcModel\ActivityGoods;
use app\model\BbcModel\ActivitySeckill;
use app\model\BbcModel\ActivitySend;
use app\model\BbcModel\ActivityStore;
use app\model\BbcModel\Store;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsBrand;
use think\facade\Db;
use app\model\BbcModel\Manager;

class ActivityService
{
    
    public function makeWhere(array $param):array
    {
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        if(empty($param['type'])){
            return Normal::returnCode(Normal::FAIL, '类型必传');
        }
        $where=[
          ['cid','=',$param['cid']],
          ['type','=',$param['type']]
        ];
        if(!empty($param['name'])){
            $where[]=['name','like','%'.trim($param['name']).'%'];
        }
        if(isset($param['status']) && $param['status'] !==''){
            $where[]=['status','=',$param['status']];
        }
        if(isset($param['sync_online']) && $param['sync_online'] !==''){
            $where[]=['sync_online','=',$param['sync_online']];
        }
        if(isset($param['is_step']) && $param['is_step'] !==''){
            $where[] = ['is_step','=',$param['is_step']];
        }
        if(!empty($param['store'])){
            $ids=ActivityStore::instance()->where("cid={$param['cid']} and (mn_sid=0 or mn_sid={$param['store']})")->column('activity_id');
            if(!empty($ids)){
                $where[]=['id','in',$ids];
            }else{
                $where[]=['id','=',0];
            }
        }
        return $where;
    }
    
    /**
     * 获取活动列表分页
     * @param array $param
     * @return array
     */
    public function getActivityListByPage(array $param):array {        
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        $where=$this->makeWhere($param);
        $list= Activity::instance()->where($where)->order('id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();    
        $total=Activity::instance()->where($where)->order('id desc')->count();
        $store= Store::instance()->lists(['cid'=>$param['cid'],'_fields_'=>'id,store_name']);
        $storeList=array_column($store,'store_name','id');
        foreach ($list as $k=>$v){
            $list[$k]['time']=date('Y-m-d',$v['begindate']).' 至 '.date('Y-m-d',$v['enddate']).' 每天'.$v['begintime'].' 至 '.$v['endtime'];
            $list[$k]['target_type']= Activity::instance()->target_type[$v['target_type']];
            $list[$k]['sync_online']= Activity::instance()->sync_online[$v['sync_online']];
            $stores=ActivityStore::instance()->lists(['cid'=>$param['cid'],'activity_id'=>$v['id']]);
            if($stores[0]['mn_sid']==0){
                $list[$k]['store_name']='全部';
            }else{
                $item='';
                foreach ($stores as $value){
                    $item.=$storeList[$value['mn_sid']].'、';
                }
                $list[$k]['store_name']=rtrim($item,'、');
            }
            $list[$k]['cd']=date('Y-m-d H:i:s',$v['cd']);
            if(in_array($param['type'],[1,2])){
                switch ($v['rule_type']){
                    case 1://买赠
                        $res= $this->getSendContent(['activity_id'=>$v['id']]);
                        break;
                    case 2://直降
                        $res= $this->getDropContent(['activity_id'=>$v['id']]);
                        break;
                    case 3://打折
                        $res= $this->getDiscountContent(['activity_id'=>$v['id']]);
                        break;
                    default:
                        $res=Normal::returnCode(Normal::FAIL, '没有活动详情');
                }
            }else if($param['type'] == 3){
                $res=Normal::returnCode(Normal::FAIL, '超级秒杀');
            }else{
                $res = $this->getBookContent(['activity_id'=>$v['id']]);
            }
            if($res['code']==Normal::SUC){
                $content=$res['data']['content'];
            }else{
                $content="未知活动规则";
            }
            $list[$k]['content']=$content;
            $list[$k]['statusname']=Activity::instance()->status[$v['status']];            
        }
        return Normal::returnCode(Normal::SUC,'获取成功',['total'=>$total,'list'=>$list]);
    }
    
    /**
     * 满赠活动详情
     * @param array $param
     * @return array
     */
    public function getSendContent(array $param):array {
        $list= ActivitySend::instance()->lists(['activity_id'=>$param['activity_id']]);
        if(empty($list)){
            return Normal::returnCode(Normal::FAIL, '没有活动详情');
        }
        $content='';
        $sendGoods=[];
        foreach ($list as $k=> $v){
            $unit=Activity::instance()->unit[$v['unit_type']];
            if($v['unit_type']==0){
                $content.='满'.round($v['full'],2).'赠'.round($v['send']).'件，';
                $title='满'.round($v['full'],2).'赠'.round($v['send']).'件';
            }else{
                $content.='满'.round($v['full'],2).$unit.'赠'.round($v['send']).'件，';
                $title='满'.round($v['full'],2).$unit.'赠'.round($v['send']).'件';
            }
            $g=Goods::instance()->info([['id','=',$v['goods_id']]]);
            $goods['img']=$g['img']??'';
            $goods['title']=$title;
            $sendGoods[]=$goods;
        }
        $content=rtrim($content,'，');
        return Normal::returnCode(Normal::SUC, '请求成功',['list'=>$list,'content'=>$content,'sendGoods'=>$sendGoods]);
    }
    
    /**
     * 直降活动详情
     * @param array $param
     * @return array
     */
    public function getDropContent(array $param):array
    {
        $list= ActivityDrop::instance()->lists(['activity_id'=>$param['activity_id']]);
        if(empty($list)){
            return Normal::returnCode(Normal::FAIL, '没有活动详情');
        }
        $content='';
        foreach ($list as $v){
            $unit=Activity::instance()->unit[$v['unit_type']];
            if($v['unit_type']==0){
                $content.='满'.round($v['full'],2).'减'.round($v['drop']).'，';
            }else{
                $content.='满'.round($v['full'],2).$unit.'减'.round($v['drop']).'，';
            }
        }
        $content=rtrim($content,'，');
        return Normal::returnCode(Normal::SUC, '请求成功',['list'=>$list,'content'=>$content]);
    }
    
    /**
     * 满折活动详情
     * @param array $param
     * @return array
     */
    public function getDiscountContent(array $param):array
    {
        $list= ActivityDiscount::instance()->lists(['activity_id'=>$param['activity_id']]);
        if(empty($list)){
            return Normal::returnCode(Normal::FAIL, '没有活动详情');
        }
        $content='';
        foreach ($list as $v){
            $unit=Activity::instance()->unit[$v['unit_type']];
            $discount=round($v['discount']/10,1);
            if($v['unit_type']==0){
                $content.='满'.round($v['full'],2).'打'.$discount.'折,';
            }else{
                $content.='满'.round($v['full'],2).$unit.'打'.$discount.'折,';
            }
        }
        $content=rtrim($content,',');
        return Normal::returnCode(Normal::SUC, '请求成功',['list'=>$list,'content'=>$content]);
    }
    
    /**
     * 拼团活动详情
     * @param array $param
     * @return array
     */
    public function getBookContent(array $param):array
    {
        $info= ActivityBook::instance()->info(['activity_id'=>$param['activity_id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL, '没有活动详情');
        }
        $content='';
        $numArr = explode(',',$info['num']);
        foreach($numArr as $v){
            $content .= $v.'人团、';
        }
        $content = rtrim($content,'、');
        return Normal::returnCode(Normal::SUC, '请求成功',['content'=>$content]);
    }
    
    /**
     * 获取活动想起
     * @param array $param
     * @return array
     */
    public function getActivityDetail(array $param):array {
        $id=$param['id'];
        $cid=$param['cid'];
        $info= Activity::instance()->info(['id'=>$id]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL, '未找到相关活动');
        }
        if($info['cid'] != $cid){
            return Normal::returnCode(Normal::FAIL, '此活动不属于你的渠道');
        }
        $info['begindate']=date('Y-m-d',$info['begindate']);
        $info['enddate']=date('Y-m-d',$info['enddate']);
        $type=$info['type'];
        if(in_array($info['type'],[1,2])){ 
            switch ($info['rule_type']){
                case 1:
                    $sendData=ActivitySend::instance()->lists(['activity_id'=>$info['id']]);
                    foreach ($sendData as $k=>$v){
                        $goods_id=$v['goods_id'];
                        $goods=Goods::instance()->info([['id','=',$goods_id],'_fields_'=>'id,name,skucode,barcode,class_id,brand_id,is_bonded,price,price_vip,price_market,price_cost,tax_free,tax_rate']);
//                        foreach ($goods as $key=>$value){
//                            $goods_class = GoodsClass::instance()->info(['id'=>$value['class_id']]);
//                            $goods[$key]['goodsclassname'] = empty($goods_class)?'':$goods_class['name'];
//                            $goods_brand = GoodsBrand::instance()->info(['id'=>$value['brand_id']]);
//                            $goods[$key]['goodsbrandname'] = empty($goods_brand)?'': $goods_brand['name'];
//                            $goods[$key]['is_bonded'] = Goods::instance()->is_bonded[$value['is_bonded']];
//                        }
                        $goods_class = GoodsClass::instance()->info(['id'=>$goods['class_id']]);
                        $goods['goodsclassname'] = empty($goods_class)?'':$goods_class['name'];
                        $goods_brand = GoodsBrand::instance()->info(['id'=>$goods['brand_id']]);
                        $goods['goodsbrandname'] = empty($goods_brand)?'': $goods_brand['name'];
                        $goods['is_bonded'] = Goods::instance()->is_bonded[$goods['is_bonded']];
                        $sendData[$k]['goodslist']=$goods;
                        $sendData[$k]['full']=round($v['full'],2);
                    }
                    $info['send']=$sendData;
                    break;
                case 2:
                    $info['drop']=ActivityDrop::instance()->lists(['activity_id'=>$info['id']]);
                    break;
                case 3:
                    $info['discount']=ActivityDiscount::instance()->lists(['activity_id'=>$info['id']]);
                    break;
            }
        }else if($info['type'] == 3){ //超级秒杀规则
            $info['activity_seckill'] = ActivitySeckill::instance()->info(['activity_id'=>$info['id']]);
        }else{ //拼团规则
            $activity_book = ActivityBook::instance()->info(['activity_id'=>$info['id']]);
            $date = $this->SecToDate($activity_book['time_limit']);
            $info['days'] = $date['days'];
            $info['hours'] = $date['hours'];
            $info['minutes'] = $date['minutes'];
            $info['imitate'] = $activity_book['imitate'];
            $info['imitate_rule'] = $activity_book['imitate_rule'];
            $info['show_book'] = $activity_book['show_book'];
            $info['buy_limit'] = $activity_book['buy_limit'];
            $info['buy_num'] = $activity_book['buy_num'];
            $info['join_type'] = $activity_book['join_type'];
            if($info['is_step'] == 1){ //阶梯拼团
                $num = explode(',',$activity_book['num']);
                $info['num'][0] = $num[0];
                $info['num'][1] = isset($num[1]) ? $num[1] : '';
                $info['num'][2] = isset($num[2]) ? $num[2] : '';
                $info['num'][3] = isset($num[3]) ? $num[3] : '';
            }else{
                $info['num'] = $activity_book['num'];
            }
            $info['imitate_days'] = 0;
            $info['imitate_hours'] = 0;
            $info['imitate_minutes'] = 10;
            if($info['imitate']==1 && $activity_book['imitate_time']>0){
                $dates = $this->SecToDate($activity_book['imitate_time']);
                $info['imitate_days'] = $dates['days'];
                $info['imitate_hours'] = $dates['hours'];
                $info['imitate_minutes'] = $dates['minutes'];
            }
        }
        $stores=ActivityStore::instance()->lists(['cid'=>$cid,'activity_id'=>$info['id']]);
        $store=Store::instance()->lists(['cid'=>$cid,'status'=>1,'check_status'=>1,'_fields_'=>'id,store_name']);
        $storeList=array_column($store,'store_name','id');
        if($stores[0]['mn_sid']==0){
            $info['store_name']=[];
            $info['mn_sids']=[];
            $info['store_data']=[];
        }else{
            $item=[];
            $ids=array_column($stores,'mn_sid');
            $info['mn_sids']=$ids;
            $info['store_data']=$ids;
            foreach ($stores as $value){
                if(isset($storeList[$value['mn_sid']])){
                    $item[$value['mn_sid']]=$storeList[$value['mn_sid']];
                }
            }
            $info['store_name']=$item;
        }
        $info['status_name']=Activity::instance()->status[$info['status']];
        if($info['type'] != 1){
            //商品促销查询商品
            $activity_goods_ids=ActivityGoods::instance()->lists(['activity_id'=>$info['id']]);
            $activity_goods=array_column($activity_goods_ids,'goods_id');
            if($info['is_step'] == 1){ //阶梯拼团
                foreach($activity_goods_ids as $v){
                    $goods_price[$v['goods_id']]['price'] = $v['price'];
                    $goods_price[$v['goods_id']]['price_second'] = $v['price_second'] == 0 ? '无' : $v['price_second'];
                    $goods_price[$v['goods_id']]['price_third'] = $v['price_third'] == 0 ? '无' : $v['price_third'];
                    $goods_price[$v['goods_id']]['price_forth'] = $v['price_forth'] == 0 ? '无' : $v['price_forth'];
                }
            }else{
                $goods_price = array_column($activity_goods_ids,'price','goods_id');
            }
            $activity_goods_list=Goods::instance()->lists([['id','in',$activity_goods],'_fields_'=>'id,name,skucode,barcode,class_id,brand_id,is_bonded,price as price_store,price_vip,price_market,price_cost,tax_free,tax_rate']);
            foreach ($activity_goods_list as $key=>$value){
                if($value['tax_free'] == 0){
                    $activity_goods_list[$key]['tax_free'] = '否';
                }else{
                    $activity_goods_list[$key]['tax_free'] = '是';
                }
                $goods_class = GoodsClass::instance()->info(['id'=>$value['class_id']]);
                $activity_goods_list[$key]['goodsclassname'] = empty($goods_class)?'':$goods_class['name'];
                $goods_brand = GoodsBrand::instance()->info(['id'=>$value['brand_id']]);
                $activity_goods_list[$key]['goodsbrandname'] = empty($goods_brand)?'':$goods_brand['name'];
                $activity_goods_list[$key]['is_bonded'] = Goods::instance()->is_bonded[$value['is_bonded']];
                if($info['is_step'] == 1){
                    $activity_goods_list[$key]['price'] = $goods_price[$value['id']]['price'];
                    $activity_goods_list[$key]['price_second'] = $goods_price[$value['id']]['price_second'];
                    $activity_goods_list[$key]['price_third'] = $goods_price[$value['id']]['price_third'];
                    $activity_goods_list[$key]['price_forth'] = $goods_price[$value['id']]['price_forth'];
                }else{
                    $activity_goods_list[$key]['price'] = $goods_price[$value['id']];
                }
                if($param['op']=='quote'){
                    $start_date=strtotime($info['begindate']);
                    $end_date=strtotime($info['enddate']);
                    $activity_ids=Activity::instance()->where("(begindate between {$start_date} and {$end_date} or enddate between {$start_date} and {$end_date}) and cid={$cid} and type={$type} and status <> 2 and id <>{$id}")->column('id');
                    if(!empty($activity_ids)){
                        $goods_ids=ActivityGoods::instance()->where([['activity_id','in',$activity_ids]])->column('goods_id');
                        if(!empty($goods_ids)){
                            if(in_array($value['id'],$goods_ids)){
                               unset($activity_goods_list[$key]);
                            }
                        }
                    }
                }
            }
            $info['goods_list']=array_values($activity_goods_list);
        }
        return Normal::returnCode(Normal::SUC, '请求成功',$info);
    }
    
    //秒转换天、时、分
    public function SecToDate($time = 0){
        $value = array(
          "years" => 0, "days" => 0, "hours" => 0,
          "minutes" => 0, "seconds" => 0,
        );
        if($time >= 31556926){
            $value["years"] = floor($time/31556926);
            $time = ($time%31556926);
        }
        if($time >= 86400){
            $value["days"] = floor($time/86400);
            $time = ($time%86400);
        }
        if($time >= 3600){
            $value["hours"] = floor($time/3600);
            $time = ($time%3600);
        }
        if($time >= 60){
            $value["minutes"] = floor($time/60);
            $time = ($time%60);
        }
        $value["seconds"] = floor($time);
        return ['days' => $value['days'],'hours'=>$value['hours'],'minutes'=>$value['minutes']];
    }
    
    /**
     * 新增活动
     * @param array $param
     * @return array
     */
    public function addData(array $param):array
    {        
        $time=time();
        if(!$param['name']){
            return Normal::returnCode(Normal::FAIL, '活动名称不能为空');
        }
        if(mb_strlen($param['name'])>15){
            return Normal::returnCode(Normal::FAIL, '促销名称最多15字');
        }
        if($param['cb_id']>0){
            return Normal::returnCode(Normal::FAIL, '不支持该功能');
        }
        $activity['name'] = $param['name'];
        $activity['target_type']=$param['target_type'];
        $activity['rule_type'] = $param['rule_type'] ?? '';
        $activity['type']=$param['type'];
        $activity['sync_online']=$param['sync_online'];
        $activity['begintime']=$param['begintime'];
        $activity['endtime']=$param['endtime'];
        $activity['remark']=$param['remark'] ?? '';
        $activity['unit_type']=$param['unit_type'];
        $activity['begindate']=strtotime($param['begindate']);
        $activity['enddate']=strtotime($param['enddate'])+86399;
        $activity['is_step'] = isset($param['is_step']) ? $param['is_step'] : 0;
        $activity['is_store'] = isset($param['is_store']) ? $param['is_store'] : 0;//是否是店铺创建的活动
        $activity['pre_notice'] = $param['pre_notice'] ?? 0;
        if($param['type']==1){//整单促销要选择活动叠加
            if($param['other_act']==1){
                $activity['act_super']=0;
                if(!isset($param['other_act_id'])){
                    return Normal::returnCode(Normal::FAIL, '请选择叠加的活动');
                }
                if(in_array(1,$param['other_act_id'])){
                    $activity['act_super']+=1;
                }
                if(in_array(2,$param['other_act_id'])){
                    $activity['act_super']+=2;
                }
            }else{
                $activity['act_super']=0;
            }
        }
        if($param['type']!=1 && empty($param['goods_ids'])){
            return Normal::returnCode(Normal::FAIL, '请选择活动商品');
        }
        if($activity['begindate']<$time){
            $activity['status']=1;
        }
        if($activity['enddate']<$time){
            return Normal::returnCode(Normal::FAIL, '结束时间不能小于当前时间');
        }
        Db::startTrans();
        try{
            if(isset($param['id'])){
                $activity['md']=time();
                $act_id=$param['id'];
                Activity::instance()->edit(['id'=>$param['id']],$activity);
            }else{
                $activity['cid']=$param['cid'];
                $activity['cb_id']=$param['cb_id']??0;
                $activity['create_staff_id']=$param['manager_id'];
                $manager= Manager::instance()->info(['id'=>$param['manager_id']]);
                $activity['create_staff_name']=$manager['name']??'';
                $activity['cd']=time();
                $act_id= Activity::instance()->add($activity);
            }
            if($param['op'] =='edit'){
                $this->deleteRule(['id'=>$param['id']]);
            }
//            $act_id=$this->add($activity);
            //活动适用店铺
                $mn_sids=$param['store_data'];
                if(empty($mn_sids)){
                    ActivityStore::instance()->add(['cid'=>$param['cid'],'cd'=>$time,'activity_id'=>$act_id,'mn_sid'=>0,'enddate'=>$activity['enddate']]);
                }else{
    //                $stores=explode(',',$param['mn_sids']);
                    foreach ($mn_sids as $v){
                        $addStore['cd']=$time;
                        $addStore['cid']=$param['cid'];
                        $addStore['activity_id']=$act_id;
                        $addStore['enddate']=$activity['enddate'];
                        $addStore['mn_sid']=$v;
                        ActivityStore::instance()->add($addStore);
                    }
                }
            if($param['type'] == 1 || $param['type'] == 2){
                //整单促销与满减促销，加盟店活动默认禁用状态
//                if(empty($mn_sids)){ //该活动适用于所有店铺
//                    $storeWhere = ['pid'=>$param['cid'],'status'=>1,'check_status'=>1,'channel_type'=>2];
//                    $join_stores = Store::instance()->where($storeWhere)->column('id');
//
//                }else{
//                    $join_stores = Store::instance()->where('id','in',$mn_sids)->where(['channel_type'=>2])->column('id');
//                }
//                if(isset($join_stores) && count($join_stores) > 0){ //存在加盟店
//                    foreach($join_stores as $k=>$v){
//                        $insertJoinStore[$k]['mn_sid'] = $v;
//                        $insertJoinStore[$k]['activity_id'] = $act_id;
//                        $insertJoinStore[$k]['cd'] = time();
//                    }
//                    Db::table('ly_store_activity')->insertAll($insertJoinStore); //写入加盟店铺活动禁用数据
//                }
            }
            //写入活动规则
            $param['activity_id']=$act_id;
            if(in_array($param['type'],[1,2])){ //整单促销与满减促销规则
                switch ($activity['rule_type']){
                    default:
                        return Normal::returnCode(Normal::FAIL, '规则类型未知');
                        break;
                    case 1://买赠
                        $res= $this->newSend($param);
                        break;
                    case 2://直降
                        $res= $this->newDrop($param);
                        break;
                    case 3://打折
                        $res= $this->newDiscount($param);
                        break;
                }
            }else if($param['type'] == 3){ //超级秒杀
                $seckillgoods=$param['goods_ids'];
                $param['goods_ids']= array_column($seckillgoods, 'goods_id');
                $param['price']=array_column($seckillgoods, 'price','goods_id');
                //判断秒杀价格是否低于结算价
                $goods_lists = Goods::instance()->where('id','in',$param['goods_ids'])->field('id,name,price_cost,price_vip,price_market,price')->select();
                $level=0;
//                if($activity['is_store']>0){
//                    $level=Store::instance()->where(['id'=>$activity['is_store']])->value('level');
//                }
                foreach($goods_lists as $k=>$v){
                    if(!isset($param['price'][$v['id']]) || empty($param['price'][$v['id']]) || !is_numeric($param['price'][$v['id']])){
                        return Normal::returnCode(Normal::FAIL, '商品《'.$goods_lists[$k]['name'].'》的秒杀价不正确');
                    }
                    if($v['price_cost']>$param['price'][$v['id']]){
                        return Normal::returnCode(Normal::FAIL, '商品《'.$goods_lists[$k]['name'].'》的秒杀价不能低于成本价');
                    }
                }
                $res = $this->newSeckillSend($param); //秒杀规则写入
            }else if($param['type'] == 4 && $activity['is_step'] == 0){ //普通拼团
                $bookgoods=$param['goods_ids'];
                $param['goods_ids']= array_column($bookgoods, 'goods_id');
                $param['price']=array_column($bookgoods, 'price','goods_id');
                //判断拼团价格是否低于结算价
                $goods_lists = Goods::instance()->where('id','in',$param['goods_ids'])->field('id,name,price_cost,price_vip,price_market,price')->select();
                foreach($goods_lists as $k=>$v){
                    if(!isset($param['price'][$v['id']][0]) || empty($param['price'][$v['id']][0]) || !is_numeric($param['price'][$v['id']][0])){
                        return Normal::returnCode(Normal::FAIL, '商品《'.$goods_lists[$k]['name'].'》的拼团价不正确');
                    }
                    if($v['price_cost']>$param['price'][$v['id']][0]){
                        return Normal::returnCode(Normal::FAIL, '商品《'.$goods_lists[$k]['name'].'》的秒杀价不能低于成本价');
                    }
                }
                $res = $this->newBookSend($param); //普通拼团规则写入

            }else if($param['type'] == 4 && $param['is_step'] == 1){ //阶梯拼团
                $step_num = $param['num'];
                if(!$step_num[0] || $step_num[0] <=0){
                    return Normal::returnCode(Normal::FAIL,'拼团人数至少填写一个阶梯人数且大于0');
                }
                foreach($step_num as $k=>$v){
                    if($v){
                        $step_num_arr[] = $v;
                    }
                    if($k != 0 && $v <= $step_num[$k - 1]){
                        return Normal::returnCode(Normal::FAIL,'拼团人数需要大于上一级阶梯');
                    }
                    if(($k+1) < count($step_num) && !$step_num[$k+1]){
                        break;
                    }
                }
                $param['num'] = $step_num_arr;
                $bookgoods=$param['goods_ids'];
                $param['goods_ids']= array_column($bookgoods, 'goods_id');
                $param['price']=array_column($bookgoods, 'price','goods_id');
                $goods_lists = Goods::instance()->where('id','in',$param['goods_ids'])->field('id,name,price_cost,price_vip,price_market,price')->select();
                foreach($goods_lists as $k=>$v){
                    if(!isset($param['price'][$v['id']]) || empty($param['price'][$v['id']])){
                        return Normal::returnCode(Normal::FAIL,'商品《'.$goods_lists[$k]['name'].'》的拼团价不正确');
                    }
                    for ($i=0; $i < count($param['num']); $i++) {
                        if($v['price_cost'] > $param['price'][$v['id']][$i]){
                            return Normal::returnCode(Normal::FAIL,'商品《'.$goods_lists[$k]['name'].'》的拼团价不能低于结算价');
                        }
                        $param['new_price'][$v['id']][] = $param['price'][$v['id']][$i];
                    }
                    unset($param['price'][$v['id']]);
                }
                $res = $this->newBookSend($param); //阶梯拼团规则写入
            }else{
                return Normal::returnCode(Normal::FAIL,'操作失败');
            }
            //写入商品
            if($param['type'] != 1){
                $result= $this->addGoods($param);
                if($result['code']==Normal::FAIL){
                    Db::rollback();
                    return $result;
                }
            }
            if($res['code']==Normal::FAIL){
                Db::rollback();
                return $res;
            }else{
                Db::commit();
                return $res;
            }

        }catch (\Exception $e){
            Db::rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }

    }
    
    /**
     * 编辑前删除活动规则
     * @param array $param
     * @return array
     */
    public function deleteRule(array $param):array{
        $info= Activity::instance()->info(['id'=>$param['id']]);
        ActivityStore::instance()->del(['activity_id'=>$param['id']]);
        if(in_array($info['type'],[1,2])){
            switch ($info['rule_type']){
                case 1:
                    ActivitySend::instance()->del(['activity_id'=>$info['id']]);
                    break;
                case 2:
                    ActivityDrop::instance()->del(['activity_id'=>$info['id']]);
                    break;
                case 3:
                    ActivityDiscount::instance()->del(['activity_id'=>$info['id']]);
                    break;
            }
        }else if($info['type'] == 3){ //秒杀规则
            ActivitySeckill::instance()->del(['activity_id'=>$info['id']]);
        }else{ //拼团规则
            ActivityBook::instance()->del(['activity_id'=>$info['id']]);
        }
        ActivityGoods::instance()->del(['activity_id'=>$info['id']]);
    }
    
    /**
     * 新增满赠活动规则
     * @param array $param
     * @return array
     */
    public function newSend(array $param):array{
        $add['cd']=time();
        $add['cid']=$param['cid'];
        $add['cid'] = $param['cb_id']??0;
        $add['activity_id']=$param['activity_id'];
        $add['unit_type']=$param['unit_type'];
        foreach ($param['send'] as $k=>$v){            
            if(empty($v['full'])){
                return Normal::returnCode(Normal::FAIL, '满足金额不能为空');
                break;
            }
            $add['full']=$v['full'];
            if(!isset($v['send']) || empty($v['send'])){
                return Normal::returnCode(Normal::FAIL, '赠送数量不能为空');
                break;
            }
            if($param['type'] == 2 && $param['unit_type'] == 1){
                if(floor($v['full']) != $v['full']){
                    return Normal::returnCode(Normal::FAIL, '商品数量必须是大于0的整数');
                    break;
                }
            }
            $add['send']=$v['send'];
            if(!isset($v['goods_id']) || empty($v['goods_id'])){
                return Normal::returnCode(Normal::FAIL, '请选择赠送商品');
                break;
            }
            if($param['type'] == 2 && $param['unit_type'] == 1){
                if(floor($v['full']) != $v['full']){
                    return Normal::returnCode(Normal::FAIL, '商品数量必须是大于0的整数');
                    break;
                }
            }
            $add['goods_id']=$v['goods_id'];            
            ActivitySend::instance()->add($add);
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    /**
     * 新增满减活动规则
     * @param array $param
     * @return array
     */
    public function newDrop(array $param):array{
        $add['cd']=time();
        $add['cid']=$param['cid'];
        $add['cid'] = $param['cb_id']??0;
        $add['activity_id']=$param['activity_id'];
        $add['unit_type']=$param['unit_type'];
        foreach ($param['drop'] as $k=>$v){
            if(empty($v['full'])){
                return Normal::returnCode(Normal::FAIL, '满足金额不能为空');
                break;
            }
            $add['full']=$v['full'];
            if(!isset($v['drop']) || empty($v['drop'])){
                return Normal::returnCode(Normal::FAIL, '减多少写清楚啊');
                break;
            }
            if($param['type'] == 2 && $param['unit_type'] == 1){
                if(floor($v['full']) != $v['full']){
                    return Normal::returnCode(Normal::FAIL, '商品数量必须是大于0的整数');
                    break;
                }
            }
            /*if($v <= $param['drop'][$k]){
                return [
                    'status'=>Normal::FAIL,
                    'msg'   =>'满减金额需大于优惠金额'
                ];
                break;
            }*/
            $add['drop']=$v['drop'];
            ActivityDrop::instance()->add($add);
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    /**
     * 新增满折活动规则
     * @param type $param
     * @return type
     */
    public function newDiscount($param){
        $add['cd']=time();
        $add['cid']=$param['cid'];
        $add['cid'] = $param['cb_id']??0;
        $add['activity_id']=$param['activity_id'];
        $add['unit_type']=$param['unit_type'];
        foreach ($param['discount'] as $k=>$v){
            if(empty($v['full'])){
                return Normal::returnCode(Normal::FAIL, '满足金额不能为空');
                break;
            }
            $add['full']=$v['full'];
            if(!isset($v['discount']) || empty($v['discount'])){
                return Normal::returnCode(Normal::FAIL, '写清楚打几折啊');
                break;
            }
            if($param['type'] == 2 && $param['unit_type'] == 1){
                if(floor($v['full']) != $v['full']){
                    return Normal::returnCode(Normal::FAIL, '商品数量必须是大于0的整数');
                    break;
                }
            }
            $add['discount']=$v['discount'];
            ActivityDiscount::instance()->add($add);
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    /**
     * 新增秒杀活动规则
     * @param array $param
     * @return array
     */
    public function newSeckillSend(array $param):array{
        $add['cd'] = time();
        $add['cid'] = $param['cid'];
        $add['cid'] = $param['cb_id']??0;
        $add['activity_id'] = $param['activity_id'];
        $add['buy_limit'] = $param['buy_limit'];
        if($add['buy_limit'] == 1){
            if(!isset($param['buy_num']) || empty($param['buy_num']) || !is_numeric($param['buy_num']) || $param['buy_num'] <=0){
                return Normal::returnCode(Normal::FAIL, '限购数量错误');
            }
            $add['buy_num'] = $param['buy_num'];
        }
        ActivitySeckill::instance()->add($add);
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    /**
     * 新增拼团活动规则
     * @param array $param
     * @return array
     */
    public function newBookSend(array $param):array{
        $add['cd'] = time();
        $add['cid'] = $param['cid'];
        $add['cid'] = $param['cb_id']??0;
        $add['activity_id'] = $param['activity_id'];
        $add['buy_limit'] = $param['buy_limit'];
        /*拼团有效期*/
        $s = 0;
        if(isset($param['time_limit'])){
            $s=$param['time_limit'];
        }else{
            if($param['days']){
                $s += $param['days'] * 24 * 60 * 60;
            }
            if($param['hours']){
                $s += $param['hours'] * 60 * 60;
            }
            if($param['minutes']){
                $s += $param['minutes'] * 60;
            }
        }
        if($s < 15 * 60 || $s > 30 * 24 * 60 * 60){
            return Normal::returnCode(Normal::FAIL, '拼团效期需在15分钟至30天之间');
        }
        $add['time_limit'] = $s;

        if($param['is_step'] == 0){ //普通拼团
            if($param['num'][0] <= 0){
                return Normal::returnCode(Normal::FAIL, '拼团人数不能小于零');
            }
            $add['num'] = $param['num'][0];
        }else{ //阶梯拼团
            $add['num'] = implode(',',$param['num']);
        }
        $add['imitate'] = $param['imitate'];
        if($param['imitate'] == 1){ //开启模拟拼团
            if($param['imitate_rule'] == 0){ //所有未拼成的团可以自动成团
                $add['imitate_rule'] = 0;
            }else if($param['imitate_rule_num'] < 0){
                return Normal::returnCode(Normal::FAIL, '模拟成团的拼团人数不正确');
            }else{
                $add['imitate_rule'] = $param['imitate_rule_num'];
            }
            $t=0;
            if($param['imitate_days']){
                $t += $param['imitate_days'] * 24 * 60 * 60;
            }
            if($param['imitate_hours']){
                $t += $param['imitate_hours'] * 60 * 60;
            }
            if($param['imitate_minutes']){
                $t += $param['imitate_minutes'] * 60;
            }
            if($t>$s){
                return Normal::returnCode(Normal::FAIL, '模拟成团时间需小于拼团有效期时间');
            }
            if($t<=0){
                return Normal::returnCode(Normal::FAIL, '模拟成团时间必须大于0');
            }
            $add['imitate_time']=$t;
        }
        $add['show_book'] = $param['show_book'];
        $add['join_type'] = $param['join_type']??1;
        if($param['buy_limit'] == 0){ //拼团不限购
            $add['buy_limit'] = 0;
        }else if($param['buy_num'] < 0){
            return Normal::returnCode(Normal::FAIL, '限购数量不正确');
        }else{
            $add['buy_num'] = $param['buy_num'];
        }
        ActivityBook::instance()->add($add);
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    /**
     * 写入活动商品
     * @param array $param
     * @return array
     */
    public function addGoods(array $param):array{
        $add['cd']=time();
        $add['activity_id']=$param['activity_id'];
        $add['cid']=$param['cid'];
        $add['cb_id']=$param['cb_id']??0;
        $insertData=[];
        $where = [];
        $activity_goods = [];
        if(in_array($param['type'],[3,4])){
            $start_date = strtotime($param['begindate']);
            $end_date = strtotime($param['enddate']) + 86399;
            if(isset($param['id']) && $param['id']){
                $where[] = ['id','neq',$param['id']];
            }
            $activity_status = Activity::instance()->where($where)->where('status','<>',2)->where('type','=',$param['type'])->where('sync_online','<>',2)->whereTime('enddate','between',[$start_date,$end_date])->column('id');
            $activity_goods = ActivityGoods::instance()->where('activity_id','in',$activity_status)->column('goods_id');
        }
        $is_store=$param['is_store']??0;
        foreach ($param['goods_ids'] as $k=>$v){
            if(isset($param['rule_type']) && $param['rule_type']==1){
                $is_bonded=Goods::instance()->info(['id'=>$v,'_fields_'=>'name,is_bonded']);
                if(in_array($is_bonded['is_bonded'],[1,2])){
                    return Normal::returnCode(Normal::FAIL, '保税和海外直邮商品《'.$is_bonded['name'].'》不能参加满赠活动');
                    break;
                }
            }
            $add['goods_id'] = $v;
            
            //判断商品是否参加了其他活动
            if(in_array($param['type'],[3,4])){
                if($is_store==0 && in_array($v,$activity_goods)){
                    $goods_name = Goods::instance()->info(['id'=>$v,'_fields_'=>'name']);
                    return Normal::returnCode(Normal::FAIL, '商品《'.$goods_name['name'].'》已参加活动');
                    break;                
                }
            }
            if($param['type'] == 3 || ($param['type'] == 4 && $param['is_step'] == 0)){ //超级秒杀与普通拼团
                if(isset($param['price'])){
                    $add['price'] = $param['price'][$v][0];
                }
            }else if($param['type'] == 4){ //阶梯拼团
                for ($i=0; $i < count($param['new_price'][$v]); $i++) { 
                    if($i == 0){
                        $add['price'] = $param['new_price'][$v][0];
                    }
                    if($i == 1){
                        $add['price_second'] = $param['new_price'][$v][1];
                    }
                    if($i == 2){
                        $add['price_third'] = $param['new_price'][$v][2];
                    }
                    if($i == 3){
                        $add['price_forth'] = $param['new_price'][$v][3];
                    }
                }
            }
            $insertData[] = $add;
        }
        $res= ActivityGoods::instance()->insertAll($insertData);
        if($res){
            return Normal::returnCode(Normal::SUC, '商品写入成功');
        }else{
            return Normal::returnCode(Normal::FAIL, '商品写入失败');
        }
    }
    
    /**
     * 终止活动
     * @param array $param
     * @return array
     */
    public function stopActivity(array $param):array {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL, '活动id必传');
        }
        $info=Activity::instance()->info(['id'=>$param['id']]);
        if($info['cid'] != $param['cid']){
            return Normal::returnCode(Normal::FAIL, '此活动不属于你的渠道');
        }
        $rs=Activity::instance()->edit(['id'=>$param['id']],['status'=>2,'md'=>time()]);
        if(!$rs){
            return Normal::returnCode(Normal::FAIL, '操作失败');
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    /**
     * 根据活动id获取门店分页
     * @param array $param
     * @return array
     */
    public function getActivityStoreByPage(array $param):array {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        $activity= Activity::instance()->info(['id'=>$param['activity_id']]);
        if(empty($activity)){
            return Normal::returnCode(Normal::FAIL, '未找到相关活动');
        }
        $storewhere=[['cid','=',$activity['cid']]];
        $stores=ActivityStore::instance()->lists(['cid'=>$param['cid'],'activity_id'=>$activity['id']]);
        if($stores[0]['mn_sid']!==0){
            $storeids= array_column($stores, 'mn_sid');
            $storewhere[]=['id','in',$storeids];
        }
        $list=Store::instance()->where($storewhere)->order('id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();
        $count=Store::instance()->where($storewhere)->count();
        $data['total']=$count;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }
}
